<template>
    <uni-forms class="form" ref="formRef" :rules="rules" :model="model.form" validateTrigger="blur">
        <uni-forms-item>
            <view class="avatar">
                <image class="img" src="/static/brand.png" mode="aspectFill" />
            </view>
        </uni-forms-item>
        <template v-if="model.isRegister">
            <uni-forms-item name="name" class="name" required key="name">
                <uni-easyinput v-model="model.form.name" placeholder="请输入姓名" prefixIcon="person" :input-border="true"
                    max-length="10" />
            </uni-forms-item>
            <uni-forms-item name="group" class="name" required key="group">
                <uni-data-select v-model="model.form.group" :localdata="model.groups" placeholder="请选择所属分组" />
            </uni-forms-item>
        </template>
        <uni-forms-item name="phone" class="phone" key="phone">
            <uni-easyinput v-model="model.form.phone" type="number" placeholder="请输入手机号码" prefixIcon="phone"
                :input-border="true" />
        </uni-forms-item>
        <uni-forms-item name="verifycode" class="vcode" key="vcode">
            <uni-easyinput v-model="model.form.verifycode" type="number" placeholder="请输入验证码" prefixIcon="notification"
                :input-border="true">
                <template v-slot:right>
                    <text class="txt" @click="send">{{model.countdown>0 ? model.countdown+'s' : '发送验证码'}}</text>
                </template>
            </uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="policy" class="policy" key="policy">
            <view class="content">
                <checkbox-group @change="hdPolicy" class="prompt">
                    <checkbox value="agree" class="checkbox" :checked="model.form.policy == 'agree'" />
                    <text class="text">我已认真阅读并同意</text>
                </checkbox-group>
                <view class="link">
                    <text class="service" @click="readPolicy" data-id="agreement">《八桂客用户服务协议》</text>
                    <text class="privacy" @click="readPolicy" data-id="privacy">《八桂客隐私政策》</text>
                </view>
            </view>
        </uni-forms-item>
        <uni-forms-item>
            <view class="submit" @click="hdRegister" v-if="model.isRegister">注 册</view>
            <view class="submit" @click="submit" v-else>登 录</view>
        </uni-forms-item>
        <uni-forms-item>
            <view class="action" @click="toggleOperation">
                {{model.isRegister?'已有账号，立即登录':'没有账号?立即注册'}}
            </view>
        </uni-forms-item>
    </uni-forms>
</template>

<script lang="ts" setup>
    import { ref } from 'vue'
    import Func from '@/utils/functions'
    import Constants from '@/utils/Constants'
    import { login, register, sendsms } from './service'
    import { useGlobalStore } from '@/stores/global'
    import Settings from '@/config/settings'
    import LocalStorage from '@/utils/localstorage'

    const global = useGlobalStore()
    const formRef = ref()
    const model = ref({
        form: {
            name: '',
            phone: '',
            verifycode: '',
            policy: '',
            group: '',
        },
        isRegister: false,
        countdown: 0,
        seconds: 60,
        intervalId: null,
        groups: [{
            text: '男生',
            value: 1
        }, {
            text: '女生',
            value: 2
        }, {
            text: '车配',
            value: 3
        }]
    })
    const rules = {
        name: {
            rules: [{
                required: true,
                errorMessage: '请输入姓名'
            }, {
                minLength: 1,
                maxLength: 10,
                errorMessage: '请输入不大于10个字符'
            }]
        },
        group: {
            rules: [{
                required: true,
                errorMessage: '请选择所属分组'
            }]
        },
        phone: {
            rules: [{
                required: true,
                errorMessage: '请输入手机号'
            }, {
                pattern: '^[1-9][0-9]{10}$',
                errorMessage: '请输入11位纯数字手机号'
            }]
        },
        verifycode: {
            rules: [{
                required: true,
                errorMessage: '请输入验证码'
            }, {
                pattern: '^\\d+$',
                errorMessage: '请输入数字字符验证码'
            }]
        },
        policy: {
            rules: [{
                required: true,
                errorMessage: '请同意服务条款'
            }, {
                pattern: '^agree$',
                errorMessage: '请同意服务条款'
            }]
        }
    }
    const toggleOperation = () => {
        model.value.isRegister = !model.value.isRegister
    }
    const send = async () => {
        try {
            await formRef.value.validateField(['phone'])
            Func.showLoading()
            if (!model.value.countdown) {
                model.value.countdown = model.value.seconds
                model.value.intervalId = setInterval(() => {
                    model.value.countdown--
                    if (model.value.countdown <= 0) {
                        model.value.countdown = 0
                        clearInterval(model.value.intervalId)
                    }
                }, 1e3)
                const res = await sendsms({
                    phone: model.value.form.phone,
                    register: model.value.isRegister,
                })
                if (res?.code === Constants.API_SUCCESS) {
                    return Func.toast({ msg: '发送成功' })
                }
                throw res
            }
        } catch (e) {
            console.log(e)
            model.value.countdown = 0
            model.value.intervalId && clearInterval(model.value.intervalId)
            e?.code == Constants.CLIENT_ERROR && (e.text = e.msg)
            e?.code == Constants.REQUEST_TOO_MANY_ATTEMPTS && (e.text = '一分钟后再尝试')
            e?.code == Constants.USER_NOT_REGISTERD && (e.text = '用户尚未注册')
            Func.hdError(e, '发送失败')
        } finally {
            Func.hideLoading()
        }
    }

    const submit = async () => {
        try {
            await formRef.value.validate()
            const modal = await Func.showModal({
                content: Func.t('Confirm submission')
            }, true)
            Func.showLoading()
            if (modal?.confirm === true) {
                let res = await login({
                    name: model.value.form.name,
                    phone: model.value.form.phone,
                    verifycode: model.value.form.verifycode,
                })
                if (res?.code === Constants.API_SUCCESS) {
                    global.setUser(res.data)
                    LocalStorage.set('user', global.getUser())
                    await Func.showToast({
                        icon: 'success',
                        title: '登录成功'
                    })
                    await Func.sleep()
                    const pages = getCurrentPages()
                    if (pages.length > 1) {
                        Func.navigateBack()
                    } else {
                        Func.switchTab({ url: Settings.homePath })
                    }
                    return
                }
                throw res
            }
        } catch (e) {
            console.log(e)
            e?.code == Constants.CLIENT_ERROR && (e.text = e.msg)
            e?.code == Constants.USER_NOT_REGISTERD && (e.text = '用户尚未注册')
            e?.code == Constants.PHONE_INCORRECT && (e.text = '登录账号错误')
            e?.code == Constants.CAPTCHA_INCORRECT && (e.text = '验证码错误')
            e?.code == Constants.VERIFIY_CODE_EXPIRED && (e.text = '验证码已过期')
            Func.hdError(e, '登录失败')
        } finally {
            Func.hideLoading()
        }
    }

    const hdPolicy = async event => {
        model.value.form.policy = 'reject'
        if (event.detail.value.includes('agree')) {
            model.value.form.policy = 'agree'
        }
    }

    const readPolicy = event => {
        let v = ''
        if (event.target.dataset.id == 'agreement') {
            v = JSON.stringify(Settings.agreement)
        } else if (event.target.dataset.id == 'privacy') {
            v = JSON.stringify(Settings.privacy)
        }
        Func.navigateTo({
            url: '/pages/policy?v=' + v
        })
    }

    const hdRegister = async () => {
        try {
            await formRef.value.validate()
            const modal = await Func.showModal({
                content: Func.t('Confirm submission')
            }, true)
            await Func.showLoading()
            if (modal?.confirm === true) {
                let res = await register({ register: model.value.isRegister, ...model.value.form })
                if (res?.code === Constants.API_SUCCESS) {
                    await Func.showToast({
                        icon: 'success',
                        title: '注册成功'
                    })
                    model.value.form.name = ''
                    model.value.form.verifycode = ''
                    model.value.isRegister = false
                    model.value.countdown = 0
                    model.value.intervalId && clearInterval(model.value.intervalId)
                    return true
                }
                throw res
            }
        } catch (e) {
            console.log(e)
            e?.code == Constants.CLIENT_ERROR && (e.text = e.msg)
            e?.code == Constants.CAPTCHA_INCORRECT && (e.text = '验证码错误')
            e?.code == Constants.VERIFIY_CODE_EXPIRED && (e.text = '验证码已过期')
            Func.hdError(e, '注册失败')
        } finally {
            Func.hideLoading()
        }
    }
</script>

<style lang="scss" scoped>
    .form {
        flex: 1;
        background-color: #fff;

        & .avatar {
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
            flex: 1;
            margin-top: 50rpx;

            & .img {
                width: 160rpx;
                height: 160rpx;
            }
        }

        & .name,
        & .phone {
            margin: 0 50rpx 44rpx 50rpx;
        }

        & .vcode {
            margin: 0 50rpx 44rpx 50rpx;
            display: flex;
            flex-direction: row;

            & .txt {
                color: #999;
                font-size: 28rpx;
                margin-right: 20rpx;
            }
        }

        & .policy {
            padding: 0 0 0 46rpx;

            & .content {

                & .prompt {
                    display: flex;
                    flex-direction: row;
                    align-items: center;

                    & .checkbox {
                        transform: scale(0.7);
                    }

                    & .text {
                        color: #5e5e5e;
                        font-size: 32rpx;
                    }
                }

                & .link {
                    display: flex;
                    flex-direction: row;
                    padding-top: 4rpx;
                }

                & .service {
                    color: #f37b1d;
                    font-size: 28rpx;
                }

                & .privacy {
                    color: #f37b1d;
                    font-size: 28rpx;
                }
            }
        }

        & .submit {
            background-color: #33aafc;
            color: #fff;
            flex: 1;
            text-align: center;
            padding: 20rpx 0;
            border-radius: 10rpx;
            margin: 0 10rpx;
        }

        & .action {
            flex: 1;
            text-align: center;
            color: #5e5e5e;
            font-size: 30rpx;
        }
    }

    :deep(.uni-easyinput__content) {
        border-radius: 50rpx !important;
        padding-left: 15rpx;
    }

    :deep(.uni-easyinput__content-input) {
        padding-left: 10rpx;
    }

    :deep(.uni-forms-item__nuve-content) {
        padding-bottom: 50rpx;
    }
    
    :deep(.uni-select){
        border-radius: 50rpx !important;
    }
    :deep(.uni-select__input-text){
        padding: 30rpx 0 30rpx 15rpx;
    }
</style>